﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QXBook.Model;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using QXBook.Utils;

namespace QXBook.Service
{
    public class OrderService : ServiceBase
    {
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="orderheader"></param>
        /// <param name="orderitems"></param>
        /// <returns></returns>
        internal int CreateOrder(OrderHeaderInfo orderheader, List<OrderItemInfo> orderitems)
        {
            DbCommand cmd = new SqlCommand();
            cmd.CommandText = @"INSERT INTO OrderHeader(UserID,OrderCode,IsPayroll,IsShipments,IsComplate,Consignee,Telphone,Address,AddDate) 
                                VALUES (@UserID,@OrderCode,@IsPayroll,@IsShipments,@IsComplate,@Consignee,@Telphone,@Address,GETDATE());SELECT @@IDENTITY";//返回主键

            string uuid = System.DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(0, 999);//一毫秒999个并发不太可能的

            base.db.AddInParameter(cmd, "@UserID", DbType.Int32, orderheader.UserID);
            base.db.AddInParameter(cmd, "@OrderCode", DbType.Int16, orderheader.OrderCode);
            base.db.AddInParameter(cmd, "@IsPayroll", DbType.Int16, (int)orderheader.IsPayroll);
            base.db.AddInParameter(cmd, "@IsShipments", DbType.Int16, (int)orderheader.IsShipments);
            base.db.AddInParameter(cmd, "@IsComplate", DbType.Int16, (int)orderheader.IsComplate);
            base.db.AddInParameter(cmd, "@Consignee", DbType.String, orderheader.Consignee);
            base.db.AddInParameter(cmd, "@Telphone", DbType.String, orderheader.Telphone);
            base.db.AddInParameter(cmd, "@Address", DbType.String, orderheader.Address);

            int identity = 0;
            object obj = base.db.ExecuteScalar(cmd);
            if (obj != null)
            {
                identity = CommonUtils.ToInt(obj);
            }

            int result = 0;
            if (orderitems != null && orderitems.Count > 0)
            {
                foreach (OrderItemInfo item in orderitems)
                {
                    cmd.CommandText = @"INSERT INTO OrderItem(HeaderID,ProductID,Price,Count,IsReturns) 
                                VALUES (@HeaderID,@ProductID,@Price,@Count,@IsReturns)";

                    base.db.AddInParameter(cmd, "@HeaderID", DbType.Int32, identity);
                    base.db.AddInParameter(cmd, "@ProductID", DbType.Int32, item.ProductID);
                    base.db.AddInParameter(cmd, "@Price", DbType.Decimal, item.Price);
                    base.db.AddInParameter(cmd, "@Count", DbType.Int32, item.Count);
                    base.db.AddInParameter(cmd, "@IsReturns", DbType.Int16, (int)item.IsReturns);
                    result += base.db.ExecuteNonQuery(cmd);
                }
            }
            
            return result;
        }
        /// <summary>
        /// 获取表头
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public OrderHeaderInfo GetOrderByOrderID(int orderID)
        {
            DbCommand cmd = new SqlCommand();

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT HeaderID,OrderCode,IsPayroll,IsShipments,IsComplate,Consignee,Address,LogisticsNum,Consignor,AddDate FROM OrderHeader");
            sbSql.Append(" WHERE HeaderID=@HeaderID ");

            cmd.CommandText = sbSql.ToString();
            base.db.AddInParameter(cmd, "@HeaderID", System.Data.DbType.Int32, orderID);
            DataSet ds = base.db.ExecuteDataSet(cmd);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                OrderHeaderInfo order = new OrderHeaderInfo();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    order.HeaderID = CommonUtils.ToInt(dr["HeaderID"]);
                    order.OrderCode = CommonUtils.ToString(dr["OrderCode"]);
                    order.IsPayroll = (YesNo)CommonUtils.ToInt(dr["IsPayroll"]);
                    order.IsShipments = (YesNo)CommonUtils.ToInt(dr["IsShipments"]);
                    order.IsComplate = (YesNo)CommonUtils.ToInt(dr["IsComplate"]);
                }
                return order;
            }

            return null;
        }
        /// <summary>
        /// 获取订单表头列表
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<OrderHeaderInfo> GetOrderList(ref PagerState ps, OrderCondition condition)
        {
            List<OrderHeaderInfo> list = new List<OrderHeaderInfo>();
            DbCommand cmd = new SqlCommand();

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT HeaderID,UserID,OrderCode,IsPayroll,IsShipments,IsComplate,Consignee,Address,LogisticsNum,Consignor,AddDate FROM OrderHeader");
            sbSql.Append(" WHERE 1=1");
            if (condition != null)
            {
                if (condition.UserID > 0)
                {
                    sbSql.Append(" AND UserID=" + condition.UserID);
                }

                if (condition.IsPayroll != YesNo.Unknow)
                {
                    sbSql.Append(" AND IsPayroll=" + (int)condition.IsPayroll);
                }

                if (condition.IsShipments != YesNo.Unknow)
                {
                    sbSql.Append(" AND IsShipments=" + (int)condition.IsShipments);
                }

                if (condition.IsComplate != YesNo.Unknow)
                {
                    sbSql.Append(" AND IsComplate=" + (int)condition.IsComplate);
                }
            }

            DataTable dt = this.GetListPager(ref ps, sbSql.ToString(), "HeaderID", cmd);

            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    OrderHeaderInfo order = new OrderHeaderInfo();
                    order.HeaderID = CommonUtils.ToInt(dr["HeaderID"]);
                    order.OrderCode = CommonUtils.ToString(dr["OrderCode"]);
                    order.IsPayroll = (YesNo)CommonUtils.ToInt(dr["IsPayroll"]);
                    order.IsShipments = (YesNo)CommonUtils.ToInt(dr["IsShipments"]);
                    order.IsComplate = (YesNo)CommonUtils.ToInt(dr["IsComplate"]);
                    order.Consignee = CommonUtils.ToString(dr["Consignee"]);
                    order.Address = CommonUtils.ToString(dr["Address"]);
                    order.LogisticsNum = CommonUtils.ToString(dr["LogisticsNum"]);
                    order.Consignor = CommonUtils.ToString(dr["Consignor"]);
                    order.AddDate = CommonUtils.ToTime(dr["AddDate"].ToString());
                    list.Add(order);
                }
            }

            return list;
        }

        /// <summary>
        /// 根据表头获取表体
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public List<OrderItemInfo> GetOrderItemByOrderID(int orderID)
        {
            List<OrderItemInfo> list = new List<OrderItemInfo>();
            DbCommand cmd = new SqlCommand();

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT A.ItemID,A.HeaderID,A.ProductID,C.Title,A.Price,A.Count,A.IsReturns FROM OrderItem A JOIN Product B ON A.ProductID=B.ProductID JOIN CoreTemplate C ON B.CoreID=C.CoreID");
            sbSql.Append(" WHERE 1=1");

            cmd.CommandText = sbSql.ToString();
            DataSet ds = base.db.ExecuteDataSet(cmd);

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    OrderItemInfo orderitem = new OrderItemInfo();
                    orderitem.ItemID = CommonUtils.ToInt(dr["ItemID"]);
                    orderitem.HeaderID = CommonUtils.ToInt(dr["HeaderID"]);
                    orderitem.ProductID = CommonUtils.ToInt(dr["ProductID"]);
                    orderitem.Product = new ProductInfo();
                    orderitem.Product.ProductID = CommonUtils.ToInt(dr["ProductID"]);
                    orderitem.Product.Title = CommonUtils.ToString(dr["Title"]);
                    orderitem.Price = CommonUtils.ToDecimal(dr["Price"]);
                    orderitem.Count = CommonUtils.ToInt(dr["Count"]);
                    list.Add(orderitem);
                }
            }

            return list;
        }

        /// <summary>
        /// 支付 调用API
        /// </summary>
        /// <returns></returns>
        public int Payroll()
        {
            return 0;
        }

        public int UpdateOrder(OrderHeaderInfo order)
        {
            string sql = "UPDATE OrderHeader SET UserID=@UserID,";
            sql += "OrderCode=@OrderCode,";
            sql += "HeaderID=@HeaderID,";
            sql += "IsPayroll=@IsPayroll,";
            sql += "IsShipments=@IsShipments,";
            sql += "IsComplate=@IsComplate,";
            sql += "Consignee=@Consignee,";
            sql += "Address=@Address,";
            sql += "LogisticsNum=@LogisticsNum,";
            sql += "Consignor=@Consignor,";
            sql += " WHERE HeaderID=@HeaderID";

            return 0;
        }

        public int UpdateOrderByCondition(int orderId, OrderCondition condition)
        {
            string sql = "UPDATE OrderHeader SET ";

            if (condition != null)
            {
                if (condition.IsPayroll != YesNo.Unknow)
                {
                    sql += "IsPayroll=" + (int)condition.IsPayroll + ",";
                }

                if (condition.IsShipments != YesNo.Unknow)
                {
                    sql += "IsShipments=" + (int)condition.IsShipments + ",";
                }

                if (condition.IsComplate != YesNo.Unknow)
                {
                    sql += "IsComplate=" + (int)condition.IsComplate + ",";
                }
            }

            sql += sql.TrimEnd(',') + " WHERE HeaderID=" + orderId;

            return base.db.ExecuteNonQuery(sql);
        }
    }
}
